package org.wdl.stockManagement.action.baseinfo;

import java.util.List;
import java.util.Map;

import org.wdl.stockManagement.service.baseinfo.IUserService;
import org.wdl.stockManagement.vo.UserInfo;

import com.opensymphony.xwork.ActionContext;
import com.opensymphony.xwork.ActionSupport;

@SuppressWarnings("serial")
public class UserAction extends ActionSupport {

	protected UserInfo user;

	protected IUserService userService;

	private String userName;

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public UserInfo getUser() {
		return user;
	}

	public void setUser(UserInfo user) {
		this.user = user;
	}

	@SuppressWarnings("unchecked")
	@Override
	public String execute() throws Exception {

		return ERROR;
	}

	public String register() throws Exception {

		userService.saveUser(user);
		return SUCCESS;
	}

	public String deleteUser() throws Exception {

		userService.deleteUser(user);
		return SUCCESS;
	}

	public String changeUserInfo() throws Exception {

		userService.changeUserInfo(user);
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	public String login() throws Exception {
		UserInfo u = userService.login(user.getUserName(), user
				.getUserPassword());
		if (u != null) {
			Map session = ActionContext.getContext().getSession();
			session.put("user", u);
			return SUCCESS;
		}

		return ERROR;

	}
	

	public String logout() throws Exception {

		Map session = ActionContext.getContext().getSession();
		session.remove("user");
		session.remove("cart");
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	public String searchUser() throws Exception {

		StringBuffer hql = new StringBuffer("from UserInfo u where 1=1 ");
		if (userName != null && userName.length() != 0)
			hql.append("and u.userName like '%" + userName + "%'");
		List users = userService.getUserByHql(hql.toString());
		Map request = (Map) ActionContext.getContext().get("request");
		request.put("users", users);
		return SUCCESS;
	}
}
